<template>
  <div>
    装备列表
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>装备列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="25">
        <!-- 搜索区域     -->
        <el-col :span="10">
          <el-input
            placeholder="请输入搜索内容"
            clearable
            @clear="getUtilList"
            v-model="queryInfo.query"
          >
            <template #append>
              <el-button icon="el-icon-search" @click="getUtilList"></el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- 下拉筛选 -->
          <el-select
            v-model="queryInfo.type"
            filterable
            placeholder="请选择装备"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.label"
              @click="getUtilList"
            >
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.value
              }}</span>
            </el-option>
          </el-select>
        </el-col>

        <el-col :span="4">
          <!-- 搜索按钮 -->
          <el-button type="primary" @click="addDialog">添加新装备 </el-button>
        </el-col>
      </el-row>
      <!-- 场地列表 border边框，stripe隔行变色 -->
      <el-table :data="utilList" border stripe>
        <!-- 索引列 -->
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="utilName" label="装备名称"> </el-table-column>
        <el-table-column prop="utilType" label="装备类型"> </el-table-column>
        <el-table-column prop="utilPrice" label="装备价格"> </el-table-column>
        <el-table-column prop="utilView" label="装备图片">
          <template v-slot="scope">
            <img width="250" height="200" :src="port + scope.row.utilView" />
          </template>
        </el-table-column>
        <el-table-column prop="utilNumber" label="装备数量"> </el-table-column>

        <el-table-column label="操作">
          <template v-slot="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="updateVisible(scope.row)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUtil(scope.row.utilId)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页部分 size-change 每页最大变化 current-change 当前最大变化 layout功能组建-->

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[1, 2, 5, 100]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 新增装备区域 -->
    <el-dialog
      title="添加新装备"
      v-model="addDialogVisible"
      width="50"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="装备名称" prop="utilName">
          <el-input v-model="addForm.utilName"></el-input>
        </el-form-item>
        <el-form-item label="装备类型" prop="utilType">
          <el-input v-model="addForm.utilType"></el-input>
        </el-form-item>
        <el-form-item label="装备价格" prop="utilPrice">
          <el-input v-model="addForm.utilPrice"></el-input>
        </el-form-item>
        <el-form-item label="装备数量" prop="utilNumber">
          <el-input v-model="addForm.utilNumber"></el-input>
        </el-form-item>
        <el-form-item label="装备图片" prop="utilView">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:9000/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="{ role: role }"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="port + imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addUtil">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 修改装备区域 -->
    <el-dialog
      title="修改装备"
      v-model="updateDialogVisible"
      width="50"
      @close="updateDialogClosed"
    >
      <el-form
        :model="updateForm"
        :rules="updateFormrules"
        ref="updateFormRef"
        label-width="80px"
      >
        <el-form-item label="装备名称" prop="utilName">
          <el-input v-model="updateForm.utilName"></el-input>
        </el-form-item>
        <el-form-item label="装备类型" prop="utilType">
          <el-input v-model="updateForm.utilType"></el-input>
        </el-form-item>
        <el-form-item label="装备价格" prop="utilPrice">
          <el-input v-model="updateForm.utilPrice"></el-input>
        </el-form-item>
        <el-form-item label="装备数量" prop="utilNumber">
          <el-input v-model="updateForm.utilNumber"></el-input>
        </el-form-item>
        <el-form-item label="装备图片" prop="utilView">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:9000/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="{ role: role }"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="port + imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateUtil">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //图片上传
      imageUrl: "",
      port: "http://localhost:9000",
      role: "",
      imageName: "",
      //查询信息实体
      queryInfo: {
        query: "", //查询信息
        type: "",
        pageNum: 1, //当前页
        pageSize: 5, //每页最大数
      },
      utilList: [], //装备列表
      total: 0, //总记录数
      addDialogVisible: false, //对话框隐藏显示状态
      updateDialogVisible: false,
      //添加表单信息
      addForm: {
        utilName: "",
        utilType: "",
        utilPrice: "",
        utilView: "",
        utilNumber: "",
      },
      //更新表单信息
      updateForm: {
        id: 0,
        utilName: "",
        utilType: "",
        utilPrice: "",
        utilView: "",
        utilNumber: "",
      },
      options: [
        {
          value: "显示全部",
          label: "",
        },
        {
          value: "snowboarding",
          label: "单板",
        },
        {
          value: "double plate",
          label: "双板",
        },
      ],
      value: "",
      //表单验证
      addFormrules: {
        utilName: [
          { required: true, message: "请输入装备名称", trigger: "blur" },
        ],
        utilType: [
          { required: true, message: "请输入装备类型", trigger: "blur" },
        ],
        utilPrice: [
          { required: true, message: "请输入装备价格", trigger: "blur" },
        ],
        utilView: [
          { required: true, message: "请上传装备图片", trigger: "blur" },
        ],
        utilNumber: [
          { required: true, message: "请输入装备数量", trigger: "blur" },
        ],
      },
      //修改表单验证
      updateFormrules: {
        utilName: [
          { required: true, message: "请输入装备名称", trigger: "blur" },
        ],
        utilType: [
          { required: true, message: "请输入装备类型", trigger: "blur" },
        ],
        utilPrice: [
          { required: true, message: "请输入装备价格", trigger: "blur" },
        ],
        utilView: [
          { required: false, message: "请上传装备图片", trigger: "blur" },
        ],
        utilNumber: [
          { required: true, message: "请输入装备数量", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getUtilList();
    this.role = encodeURIComponent(sessionStorage.getItem("role"));
  },
  methods: {
    async getUtilList() {
      const { data: res } = await this.$http.get("allUtil", {
        params: this.queryInfo,
      });
      this.utilList = res.data;
      console.log(res.data);
      this.total = res.numbers;
    },
    //最大数
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getUserList();
    },
    //pageNum的触发动作
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getUtilList();
    },
    //监听添加场地的操作
    addDialogClosed() {
      this.imageUrl = "";
      this.$refs.addFormRef.resetFields();
    },
    updateDialogClosed() {
      this.imageUrl = "";
      this.$refs.updateFormRef.resetFields();
    },
    addUtil() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("addUtil", this.addForm);
        if (res != "success") return this.$message.error("操作失败");
        this.$message.success("操作成功");
        this.addDialogVisible = false;
        this.getUtilList();
      });
    },
    addDialog() {
      this.addForm.utilView = "";
      this.addDialogVisible = true;
    },
    //根据主键删除设备信息
    async deleteUtil(utilId) {
      console.log(utilId);
      const confirmResult = await this.$confirm(
        "此操作将永久删除场地，是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult != "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete(
        "deleteUtil?utilId=" + utilId
      );
      console.log(res);
      if (res.data != "success") {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getUtilList();
    },
    updateVisible(utilInfo) {
      (this.updateDialogVisible = true),
        (this.updateForm.utilName = utilInfo.utilName),
        (this.updateForm.utilType = utilInfo.utilType),
        (this.updateForm.utilPrice = utilInfo.utilPrice),
        (this.imageUrl = utilInfo.utilView),
        (this.updateForm.utilNumber = utilInfo.utilNumber),
        (this.updateForm.utilId = utilInfo.utilId);
      this.updateForm.utilView = utilInfo.utilView;
    },

    async updateUtil() {
      this.$refs.updateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "updateUtil",
          this.updateForm
        );
        console.log(this.updateForm);
        if (res != "success") return this.$message.error("操作失败");
        this.$message.success("操作成功");
        this.updateDialogVisible = false;
        this.getUtilList();
      });
    },
    handleSave() {
      // 向后端发送 数据
      this.pojo.img = this.imageUrl;
      manager.update(this.id, this.pojo).then((res) => {
        // 修改 或者新增成功
        this.$message({
          message: res.msg,
          type: res.code === 20000 ? "success" : "error",
        });
        if (res.code === 20000) {

          this.fetchData();
        }
        this.dialogFormVisible = false;
      });
    },
    handleAvatarSuccess(res, file) {
      console.log(res);
      this.imageUrl = res.filename;
      this.addForm.utilView = this.imageUrl;
      console.log(this.imageUrl);
      this.updateForm.utilView = this.imageUrl;
      // console.log(file.raw)
      // this.imageUrl = URL.createObjectURL(file.raw)
      // 这句话绑定的是node返回的图片给你，应该发挥服务器给的图片地址
      // 保存提交时候还需要pojo.image=this.imageUrl这样就可以吧图片保存到服务器数据库里面
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>
<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 17px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 290px;
  height: 200px;
  display: block;
}
.form-item {
  margin-left: 10px;
  text-align: center;
  vertical-align: middle;
  margin-bottom: 22px;
  margin-top: 22px;
}
.topbutton {
  margin-top: 22px;
}
</style>
